package com.ygqh.baby.controller.mobile;

import com.fasterxml.jackson.databind.util.JSONPObject;
import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.ProductStatus;
import com.ygqh.baby.ao.SalesPlatform;
import com.ygqh.baby.model.ProductListRequestParam;
import com.ygqh.baby.model.YgProduct4ListModel;
import com.ygqh.baby.po.YgCategory;
import com.ygqh.baby.service.YgCategoryService;
import com.ygqh.baby.service.YgProductService;
import com.ygqh.baby.solr.YgSolrClient;
import org.apache.commons.lang.StringUtils;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrQuery.ORDER;
import org.apache.solr.client.solrj.SolrRequest.METHOD;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Controller
@RequestMapping("/solr/product")
public class ProductSolrController extends BaseController {
    @Autowired
    private YgProductService ygProductService;
    @Autowired
    private YgCategoryService ygCategoryService;

    @RequestMapping("/list")
    @ResponseBody
    public JSONPObject list(ProductListRequestParam param) {
        param.setSalesPlatform(SalesPlatform.Yiigoo.name());
        if (param.getSaleStatus() == null) {
            param.setSaleStatus(ProductStatus.OnSale);
        }
        try {
            SolrClient solrClient = YgSolrClient.INSTANCE.getSolrClient();
            System.err.println("ping solr  result:" + solrClient.ping().toString());
            SolrQuery query = new SolrQuery();


            StringBuilder sb = new StringBuilder();
            String productName = param.getProductName();
            if (StringUtil.isNotBlank(productName)) {
                sb.append("productName:").append(productName)
                        .append(" OR ").append("tags:").append(productName)
                        .append(" OR ").append("basicAttribute:").append(productName)
                        .append(" OR ").append("sizeNames:").append(productName)
                        .append(" OR ").append("categoryNames:").append(productName);
            } else {
                sb.append("*:*");
            }
            query.setQuery(sb.toString());

            if (param.getCategoryIds() != null && param.getCategoryIds().length > 0) {
                List<Long> categoryIds = getThirdLevelCategoryIds(param.getCategoryIds());
                String cids = StringUtils.join(categoryIds, " OR ");
                query.addFilterQuery("categoryId:" + "[" + cids + "]");
            }

            if (param.getIsPreProduct() != null) {
                if (param.getIsPreProduct()) {
                    query.addFilterQuery("preSaleDate:*");
                } else {
                    query.addFilterQuery("-preSaleDate:*");
                }
            }
            if (StringUtils.isNotBlank(param.getGender()) && !param.getGender().equals("0,1")) {
                query.addFilterQuery("gender:" + param.getGender());
            }
            if (param.getTags() != null) {
                query.addFilterQuery("tags:" + param.getTags());
            }
            if (param.getSupplierId() != null) {
                query.addFilterQuery("supplierId:" + param.getSupplierId());
            }
            if (param.getSaleStatus() != null) {
                query.addFilterQuery("saleStatus:" + param.getSaleStatus());
            }
            if (param.getSizeName() != null && param.getSizeName().length > 0) {
                StringBuilder sizeNames = new StringBuilder();
                for (String select : param.getSizeName()) {
                    sizeNames.append("sizeNames:").append(select).append(" OR ");
                }
                String substring = sizeNames.substring(0, sizeNames.length() - 4);
                query.addFilterQuery(substring);
            }
            if (param.getSelect1() != null && param.getSelect1().length > 0) {
                StringBuilder select1 = new StringBuilder();
                for (String select : param.getSelect1()) {
                    select1.append("categoryNames:").append("\"").append(select).append("\"")
                            .append(" OR ");
                }
                String substring = select1.substring(0, select1.length() - 4);
                query.addFilterQuery(substring);
            }
            if (param.getSelect2() != null && param.getSelect2().length > 0) {
                StringBuilder select2 = new StringBuilder();
                for (String select : param.getSelect2()) {
                    select2.append("categoryNames:").append("\"").append(select).append("\"")
                            .append(" OR ");
                }
                String substring = select2.substring(0, select2.length() - 4);
                query.addFilterQuery(substring);
            }
            if (param.getSelect3() != null && param.getSelect3().length > 0) {
                StringBuilder select3 = new StringBuilder();
                for (String select : param.getSelect3()) {
                    select3.append("basicAttribute:").append("\"").append(select).append("\"")
                            .append(" OR ").append("tags:").append("\"").append(select).append("\"").append(" OR ");
                }
                String substring = select3.substring(0, select3.length() - 4);
                query.addFilterQuery(substring);
            }
            if (param.getSalesPlatform() != null) {
                query.addFilterQuery("salesPlatform:\"" + param.getSalesPlatform() + "\"");
            }

            // 排序
            String sortKey = param.getSortKey();
            if (StringUtils.isNotBlank(sortKey)) {
                if ("product_sale_price".equals(sortKey)) {
                    sortKey = "sortSalePrice";
                }
                String solrSortColumn = this.getSolrSortColumn(sortKey);
                query.setSort(solrSortColumn, ORDER.valueOf(param.getDir()));
            } else if (!param.isSearch()) {
                query.setSort("saleTime", ORDER.desc);
            }
            // 分页
            if (param.getStart() != null) {
                query.setStart(param.getStart());
                query.setRows(param.getLimit());
            }
            QueryResponse response = solrClient.query(query, METHOD.POST);
            if (response.getResults().size() == 0) {
                List<YgProduct4ListModel> findList = ygProductService.findList(param);
                return new JSONPObject(param.getCallback(), Message.success(findList));
            }
            return new JSONPObject(param.getCallback(), Message.success(response.getResults()));
        } catch (Exception e) {
            e.printStackTrace();
            List<YgProduct4ListModel> findList = ygProductService.findList(param);
            return new JSONPObject(param.getCallback(), Message.success(findList));
        }
    }

    private List<Long> getThirdLevelCategoryIds(Long[] categoryId) {
        List<YgCategory> categorys = ygCategoryService.findByIds(categoryId);
        // 存放三级id
        List<Long> cids = new ArrayList<>();
        if (categorys != null && categorys.size() > 0) {
            // 存放二级id
            List<Long> ids = new ArrayList<>();
            for (YgCategory category : categorys) {
                if (category.getLevel().equals(Long.valueOf("2"))) {
                    ids.add(category.getId());
                } else {
                    cids.add(category.getId());
                }
            }
            List<YgCategory> categories = ygCategoryService.findByParentIds(ids);
            categories.forEach((cate) -> cids.add(cate.getId()));
        } else {
            if (categoryId != null) {
                cids.addAll(Arrays.asList(categoryId));
            }
        }
        return cids;

    }

    public String getSolrSortColumn(String sortKey) {
        if (!sortKey.contains("_")) {
            return sortKey;
        }
        String[] split = sortKey.split("_");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < split.length; i++) {
            String string = split[i];
            if (i > 0) {
                String first = string.substring(0, 1);
                String last = string.substring(1);
                string = first.toUpperCase() + last;
            }
            sb.append(string);
        }
        return sb.toString();
    }

}
